package com.ytjj.qmyx.data.runner;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dingtalk.api.response.OapiDccOrderQueryResponse;
import com.ytjj.common.dto.mqdto.OrderRecordDto;
import com.ytjj.qmyx.data.config.SanTongApiConfig;
import com.ytjj.qmyx.data.model.MobileVO;
import com.ytjj.qmyx.data.model.mongo.PageStatistics;
//import com.ytjj.qmyx.data.service.KafkaSendService;
import com.ytjj.qmyx.data.service.OrdersService;
import com.ytjj.qmyx.data.util.EncryptUtil;
import com.ytjj.qmyx.data.util.SmsWayUtil;
import com.ytjj.qmyx.mall.model.Orders;
import com.ytjj.qmyx.mall.model.OrdersInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Slf4j
@Component
public class DataRunner implements ApplicationRunner {

    @Value("${spring.profiles.active}")
    private String env;

    @Resource
    private SanTongApiConfig sanTongApiConfig;

//    @Autowired
//    private KafkaSendService kafkaSendService;

    @Autowired
    private OrdersService ordersService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        if("develop".equals(env)) {
            log.info("run");
            //testKafka();
            //testHisOrderToKafka();
        }
//        try {
//            batchSendSmsWithSantong();
//        }catch (Exception e){
//            e.printStackTrace();
//        }
    }

    /**
     * 使用欣易辰通道补发短信
     * @throws Exception
     */
    private void batchSendSms() throws Exception {
        File file=new File("/mnt/guobao/batchsms.xlsx");
        if(!file.exists()){
            log.warn("批量发送未发货提醒短信，文件不存在!");
            return;
        }
        Sheet sheet = new Sheet(1, 0, MobileVO.class);
        List<Object> list = EasyExcelFactory.read(new BufferedInputStream(new FileInputStream(file)), sheet);
        log.info("批量发送未发货提醒短信，待发送条数：{}",list.size());
        for(Object o:list) {
            MobileVO mobileVO = (MobileVO) o;
            String productName = mobileVO.getProduct();
            if(StringUtils.isNotBlank(productName)) {
                if (productName.length() > 10) {
                    productName = productName.substring(0, 9) + "...";
                }
            }
            //【XXXX优品2】尊敬的用户，您在本平台购买的XXXX因疫情原因延迟发货，如需帮助请联系客服：XXX-XXXX-XXX
            //String content="【XXXX优品2】尊敬的用户，您在本平台购买的"+productName+"因疫情原因延迟发货，更多详情请联系客服：400-xxxx-xxx";
//            String content="【XXXX优品2】尊敬的顾客您好，您在本平台购买的商品，因您所在地区受疫情、交通管制影响，快递无法正常揽收，还请您耐心等待，待物流恢复会第一时间安排，给您造成不便深感歉意，感谢您的支持，若有疑问打开微信公众号搜索“XXXX优品2”联系人工客服，平台热线4000xxxx。";
//            JSONObject jsonObject = SmsWayUtil.sendSmsWithResult(mobileVO.getMobile(), content);
//            log.info("批量发送未发货提醒短信，结果：{}",jsonObject.toJSONString());
        }
    }

    /**
     * 使用大汉通道补发短信
     * @throws Exception
     */
    private void batchSendSmsWithSantong() throws Exception {
        File file=new File("/mnt/guobao/batchsms.xlsx");
        if(!file.exists()){
            log.warn("批量发送未发货提醒短信，文件不存在!");
            return;
        }
        Sheet sheet = new Sheet(1, 0, MobileVO.class);
        List<Object> list = EasyExcelFactory.read(new BufferedInputStream(new FileInputStream(file)), sheet);
        log.info("批量发送未发货提醒短信，待发送条数：{}",list.size());
        for(Object o:list) {
            MobileVO mobileVO = (MobileVO) o;
            String[] phones = {mobileVO.getMobile()};
//            String result_sto = EncryptUtil.sendSanTong(sanTongApiConfig.getUrl(), sanTongApiConfig.getAccount(), sanTongApiConfig.getPassword(), phones, mobileVO.getProduct());
           String result_sto= EncryptUtil.sendSanTong(sanTongApiConfig.getUrl(), sanTongApiConfig.getAccount(), sanTongApiConfig.getPassword(), phones, "您好！非常抱歉，您在本平台购买的商品因疫情影响需延迟发货，具体以快递揽收时间为准，由此给您带来的不便敬请谅解！如有疑问请拨打服务热线4000xxx，感谢您的理解与支持！点击下方链接可自助查询订单或联系在线客服 t..com/kf","【XXXX优品】");
            log.info("批量发送未发货提醒短信，结果：{}",result_sto);
        }
    }
    private void testKafka(){
        PageStatistics pageStatistics=new PageStatistics();
        pageStatistics.setBrowseTime(System.currentTimeMillis());
        pageStatistics.setChannel("test");
        pageStatistics.setCreateTime(new Date());
        pageStatistics.setDayTime("2021-04-22");
        pageStatistics.setFromPage("/index");
        pageStatistics.setHourTime(12);
        pageStatistics.setIp("");
        pageStatistics.setIsNewUser(0);
        pageStatistics.setPathCode("");
        pageStatistics.setPlatform("h5");
        pageStatistics.setUuid(UUID.randomUUID().toString());
//        boolean sendStatus=kafkaSendService.sendPvMsg(JSONObject.toJSONString(pageStatistics));
        log.info("sendPvStatus={}",true);

        OrderRecordDto orderRecordDto=new OrderRecordDto();
        orderRecordDto.setActivityType("CASH_SCORE");
        orderRecordDto.setAddress("西乡");
        orderRecordDto.setArea("宝安区");
        orderRecordDto.setChannel("ma-sms-88");
        orderRecordDto.setCity("深圳市");
        orderRecordDto.setCostPrice(new BigDecimal(100));
        orderRecordDto.setCreateTime(new Date());
        orderRecordDto.setIsAddress(1);
        orderRecordDto.setIsFirstBuy(1);
        orderRecordDto.setOrderId(89778);
        orderRecordDto.setOrderInfoId(98876);
        orderRecordDto.setOrderNo("G2021042112409");
        orderRecordDto.setOriginalPrice(new BigDecimal(899));
        orderRecordDto.setIsPay(0);
        orderRecordDto.setPaySource("wx");
        orderRecordDto.setPlatform("h5");
        orderRecordDto.setPrice(new BigDecimal(198));
        orderRecordDto.setProductId(1001);
        orderRecordDto.setProductName("测试商品");
        orderRecordDto.setProvince("广东省");
        orderRecordDto.setUserId(9890);
        orderRecordDto.setUuid(UUID.randomUUID().toString());
        log.info("sendOrderRecord={}",JSONObject.toJSONString(orderRecordDto));
//        sendStatus=kafkaSendService.sendOrderRecordMsg(JSONObject.toJSONString(orderRecordDto));
        log.info("sendOrderRecordStatus={}",true);
    }

    private void testHisOrderToKafka(){
        List<OrdersInfo> ordersInfoList=ordersService.queryOrdersList("2021-05-20",1,10000);
        OrderRecordDto orderRecordDto=null;
        Orders orders=null;
        int success=0;
        int fail=0;
        for(OrdersInfo ordersInfo:ordersInfoList){
            orders=ordersService.findOrderByOrderId(ordersInfo.getOrderId());
            orderRecordDto=new OrderRecordDto();
            orderRecordDto.setPayTime(orders.getPayTime());
            orderRecordDto.setUuid(""+orders.getUserId());
            orderRecordDto.setUserId(orders.getUserId());
            orderRecordDto.setProvince(orders.getProvince());
            orderRecordDto.setProductName(ordersInfo.getProductName());
            orderRecordDto.setProductId(ordersInfo.getProductId());
            orderRecordDto.setPrice(ordersInfo.getProductPrice());
            orderRecordDto.setPlatform(orders.getOrderSource());
            orderRecordDto.setPaySource(orders.getPaySource());
            orderRecordDto.setIsPay(orders.getIsPay().intValue());
            orderRecordDto.setOriginalPrice(ordersInfo.getProductOprice());
            orderRecordDto.setOrderNo(orders.getOrderNo());
            orderRecordDto.setOrderInfoId(ordersInfo.getId());
            orderRecordDto.setOrderId(orders.getId());
            orderRecordDto.setIsFirstBuy(orders.getIsFirstBuy());
            if(StringUtils.isNotBlank(orders.getUserAddress())) {
                orderRecordDto.setIsAddress(1);
            }else{
                orderRecordDto.setIsAddress(0);
            }
            orderRecordDto.setCreateTime(orders.getCreateTime());
            orderRecordDto.setCostPrice(ordersInfo.getCostPrice());
            orderRecordDto.setCity(orders.getCity());
            orderRecordDto.setChannel(orders.getChannel());
            orderRecordDto.setArea(orders.getArea());
            orderRecordDto.setAddress(orders.getAddress());
            orderRecordDto.setActivityType(ordersInfo.getActivityType());
            orderRecordDto.setPayType(orders.getPayType());
            orderRecordDto.setUpdateTime(orders.getUpdateTime());
            orderRecordDto.setUserAddress(orders.getUserAddress());
            log.info(ordersInfo.getProductName());
//            boolean sendStatus=kafkaSendService.sendOrderRecordNewMsg(JSONObject.toJSONString(orderRecordDto));
            log.info("sendOrderRecordStatus={}",true);
            if(true){
                success++;
            }else{
                fail++;
            }
        }
        log.info("成功{}条，失败{}条",success,fail);
    }
}
